from flask import request, jsonify, current_app
from flask_jwt_extended import jwt_required
from ..services import AIAnalysisService
from ..utils import success_response, error_response
from . import api

@api.route('/ai_analyses', methods=['GET'])
@jwt_required()
def get_ai_analyses():
    """获取AI分析历史列表"""
    try:
        page = int(request.args.get('page', 1))
        per_page = int(request.args.get('limit', 10))
        keyword = request.args.get('keyword', '')
        start_date = request.args.get('start_date')
        end_date = request.args.get('end_date')
        
        result = AIAnalysisService.get_ai_analyses(
            page=page, 
            per_page=per_page, 
            keyword=keyword,
            start_date=start_date,
            end_date=end_date
        )
        
        return success_response(result, '获取成功')
    except Exception as e:
        current_app.logger.error(f'获取AI分析历史列表错误: {str(e)}')
        return error_response('获取AI分析历史列表失败', 500)

@api.route('/ai_analyses', methods=['POST'])
@jwt_required()
def create_ai_analysis():
    """创建AI分析记录"""
    try:
        data = request.get_json()
        
        # 验证必要字段
        if not data.get('intersection_name'):
            return error_response('路口名称不能为空', 400)
        
        analysis = AIAnalysisService.create_ai_analysis(data)
        return success_response(analysis.to_dict(), '分析记录已保存', 201)
    except Exception as e:
        current_app.logger.error(f'创建AI分析记录错误: {str(e)}')
        return error_response('创建AI分析记录失败', 500)

@api.route('/ai_analyses/<int:analysis_id>', methods=['GET'])
@jwt_required()
def get_ai_analysis(analysis_id):
    """根据ID获取AI分析记录"""
    try:
        analysis = AIAnalysisService.get_ai_analysis_by_id(analysis_id)
        if not analysis:
            return error_response('AI分析记录不存在', 404)
        
        return success_response(analysis.to_dict(), '获取成功')
    except Exception as e:
        current_app.logger.error(f'获取AI分析记录错误: {str(e)}')
        return error_response('获取AI分析记录失败', 500)

@api.route('/ai_analyses/<int:analysis_id>', methods=['PUT'])
@jwt_required()
def update_ai_analysis(analysis_id):
    """更新AI分析记录"""
    try:
        analysis = AIAnalysisService.get_ai_analysis_by_id(analysis_id)
        if not analysis:
            return error_response('AI分析记录不存在', 404)
        
        data = request.get_json()
        updated_analysis = AIAnalysisService.update_ai_analysis(analysis_id, data)
        
        return success_response(updated_analysis.to_dict(), '更新成功')
    except Exception as e:
        current_app.logger.error(f'更新AI分析记录错误: {str(e)}')
        return error_response('更新AI分析记录失败', 500)

@api.route('/ai_analyses/<int:analysis_id>', methods=['DELETE'])
@jwt_required()
def delete_ai_analysis(analysis_id):
    """删除AI分析记录"""
    try:
        result = AIAnalysisService.delete_ai_analysis(analysis_id)
        if not result:
            return error_response('AI分析记录不存在', 404)
        
        return success_response(None, '删除成功')
    except Exception as e:
        current_app.logger.error(f'删除AI分析记录错误: {str(e)}')
        return error_response('删除AI分析记录失败', 500)